package com.yzy.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzy.common.Result;
import com.yzy.entity.Exam;
import com.yzy.entity.Sign;
import com.yzy.entity.Student;
import com.yzy.service.ISignService;
import com.yzy.service.impl.ExamServiceImpl;
import com.yzy.utils.StuTokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * ExamController
 *
 * @author 杨子宇
 * @createTime 2023-04-21
 */
@RestController
@RequestMapping("/exam")
public class ExamController {

    @Resource
    private ExamServiceImpl examService;

    @Resource
    private ISignService signService;

    /**
     * 查询全部
     */
    @GetMapping
    public List<Exam> findAll() {
        return examService.findAll();
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Exam findById(@PathVariable Integer id) {
        return examService.findById(id);
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String room,
                           @RequestParam(defaultValue = "") String invigilator,
                           @RequestParam(defaultValue = "") String state) {
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();
        if (!"".equals(name)) {
            queryWrapper.or().like("name", name);
        }
        if (!"".equals(room)) {
            queryWrapper.or().like("room", room);
        }
        if (!"".equals(invigilator)) {
            queryWrapper.or().like("invigilator", invigilator);
        }
        if (!"".equals(state)) {
            queryWrapper.or().like("state", state);
        }
        Page<Exam> page = examService.page(new Page<>(pageNum, pageSize), queryWrapper);
        for (Exam exam : page.getRecords()) {
            setState(exam);
            examService.updateById(exam);
        }
        return Result.success(page);
    }

    /**
     * 考试状态查询
     */
    @GetMapping("/page/front")
    public Result findPageFront(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<>();

        Page<Exam> page = examService.page(new Page<>(pageNum, pageSize), queryWrapper);
        Student currentStudent = StuTokenUtils.getCurrentStudent();
        if (currentStudent != null) {
            queryWrapper.eq("username", currentStudent.getUsername());
        }

        // 查出当前学生所报名的考试
        List<Sign> signList = signService.list(new QueryWrapper<Sign>().eq("student_id", currentStudent.getId()));
        for (Exam exam : page.getRecords()) {
            exam.setEnable(false);
            Integer examId = exam.getId();
            signList.stream().filter(sign -> sign.getExamId().equals(examId)).findFirst().ifPresent(sign -> {
                // 当且仅当当前学生的报名列表里有这个考试，而且审核通过，才设置开始考试状态按钮
                exam.setEnable("审核已通过".equals(sign.getState()));
            });
            setState(exam);
            examService.updateById(exam);
        }
        return Result.success(page);
    }

    /**
     * 设置考试状态
     */
    private void setState(Exam exam) {
        String time = exam.getTime();
        DateTime dateTime = DateUtil.parse(time, "yyyy-MM-dd HH:mm");
        Date now = new Date();
        if (DateUtil.compare(dateTime, now) <= 0 && DateUtil.compare(DateUtil.offsetMinute(dateTime, exam.getDuration()), now) >= 0) {
            exam.setState("进行中");
        } else if (DateUtil.compare(dateTime, now) > 0) {
            exam.setState("未开始");
        } else {
            exam.setState("已结束");
        }
    }

    /**
     * 新增或修改
     */
    @PostMapping
    public boolean insertOrUpdate(@RequestBody Exam exam) {
        return examService.insertOrUpdate(exam);
    }

    /**
     * 根据id删除
     */
    @DeleteMapping("/{id}")
    public boolean deleteById(@PathVariable Integer id) {
        return examService.deleteById(id);
    }

    /**
     * 批量删除
     */
    @PostMapping("/del/batch")
    private boolean deleteExams(@RequestBody List<Integer> ids) {
        return examService.deleteExams(ids);
    }
}
